using hao_Common.Response.Extensions;
using hao_Jwt;
using User.Service.User;
using User.Service.Address;
using hao_Common.Dapper.Db;
using Microsoft.Extensions.DependencyInjection;
using hao_Reppsitory;
using hao_Reppsitory.User;
using User.Service;
using Dapper;  // 添加这行
using hao_Common.Dapper.TypeHandlers;  // 添加这行
using User.Service.Role;
using Microsoft.OpenApi.Models;  // 添加这行
using hao_Common.Consul.Extensions; // 添加Consul命名空间
using hao_Common.AutoMapper.Extensions; // 添加AutoMapper扩展引用
using hao_Common.Logging.Extensions;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog日志
builder.Host.AddSerilog(builder.Configuration);

// 配置Dapper类型映射 - 在其他服务注册之前添加
SqlMapper.AddTypeHandler(new GuidTypeHandler());
SqlMapper.AddTypeHandler(new NullableGuidTypeHandler());

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

// 添加日志服务
builder.Services.AddLogging(builder.Configuration);

// 添加Consul服务注册
// 注册 Consul 服务
builder.Services.AddConsul(builder.Configuration);

// 注册 HttpClient
builder.Services.AddHttpClient();

// 添加健康检查
builder.Services.AddHealthChecks();

// 配置Swagger支持JWT Bearer认证
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo 
    { 
        Title = "Hao User API", 
        Version = "v1",
        Description = "用户管理API接口文档"
    });
    
    // 添加JWT Bearer认证定义
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    
    // 添加安全要求
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

// 注册数据库连接工厂 - 修正：传递IConfiguration而不是string
builder.Services.AddSingleton<IDbConnectionFactory>(provider =>
    new DapperDbConnectionFactory(builder.Configuration));

// 注册仓储和服务
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IUserRoleRepository, UserRoleRepository>();
builder.Services.AddScoped<IAddressRepository, AddressRepository>();
// 注册HttpClient用于服务间调用
builder.Services.AddHttpClient();
// 注册服务
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IRoleService, RoleService>();
builder.Services.AddScoped<IAddressService, AddressService>();

// 注册JWT服务
builder.Services.AddJwtAuthentication(builder.Configuration);

// 在服务注册部分添加
builder.Services.AddAutoMapperService(
    typeof(Program).Assembly,
    typeof(hao_Common.AutoMapper.Profiles.BaseProfile).Assembly
);

var app = builder.Build();
// 测试数据库连接
var factory = app.Services.GetRequiredService<IDbConnectionFactory>() as DapperDbConnectionFactory;
if (factory != null && !factory.TestConnection())
{
    throw new Exception("数据库连接失败，请检查连接字符串配置！");
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 添加请求日志中间件
app.UseRequestLogging();

// 添加全局异常处理中间件（应该在其他中间件之前）
app.UseGlobalExceptionHandler();

// 添加健康检查端点
// 配置健康检查端点
app.MapHealthChecks("/health");

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();
